package com.kwan.xframe.record.audio;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;
import android.widget.Toast;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.kwan.xframe.R;
import com.kwan.xframe.mvvm.view.activity.BaseActivity;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.ViewDataBinding;
import timber.log.Timber;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public abstract class BaseRecordActivity<V extends ViewDataBinding> extends BaseActivity<V> {


	RecorderManager mAudioRecord;
	public boolean hasPermission;
	TimerManager timer;

	private String[] permissions = new String[]{
			Manifest.permission.RECORD_AUDIO,
			READ_EXTERNAL_STORAGE,
			WRITE_EXTERNAL_STORAGE
	};

	private static final int PERMISSIONS_REQUEST = 1001;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);


		state = STATE_STOP;
		//计时器初始化
		timer = new TimerManager();
		timer.set(getChronometer());

		mAudioRecord = new RecorderManager();
		mAudioRecord.changeSampleRate(44100);

		launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
				new ActivityResultCallback<ActivityResult>() {
					@Override
					public void onActivityResult(ActivityResult result) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
							if (Environment.isExternalStorageManager()) {
								hasPermission = true;
								ToastUtils.showLong("权限获取成功");
							} else {
								hasPermission = false;
								ToastUtils.showLong("权限获取失败");
							}
						}
					}
				});
		//申请权限
		hasPermission = checkPermission();
		if (!hasPermission) {
			requestPermission();
		}
	}


	/**
	 *
	 *  android 计时控件
	 *  @return  <Chronometer
	 *  app:layout_constraintTop_toTopOf="parent"
	 *  android:id="@+id/timer"
	 *  android:layout_width="match_parent"
	 *  android:layout_height="wrap_content"
	 *  android:format="00:00:00"
	 *  android:gravity="center"
	 *  android:textSize="@dimen/txt_16" />
	 */

	protected abstract Chronometer getChronometer();

	/**
	 * 是否已经开始播放，0-停止，1-开始，2-暂停
	 */
	private int state;
	private final int STATE_STOP = 0;
	private final int STATE_START = 1;
	private final int STATE_PAUSE = 2;


	public void start(View view) {

		if (!hasPermission) {
			ToastUtils.showLong("请先录音开启权限");
			requestPermission();
			onNoPermission();
			return;
		}

		if (state == STATE_STOP) {//开始录音
			Timber.d("开始录音..");
			//录音相关
			mAudioRecord.create();
			mAudioRecord.start();
			//计时器相关
			state = STATE_START;
			timer.start();
			onRecordStart();
		} else if (state == STATE_START) {//点击了暂停
			Timber.d("暂停录音..");
			mAudioRecord.pause();
			timer.pause();
			state = STATE_PAUSE;
			onRecordPause();
		} else {//暂停后重新开始
			Timber.d("重新开始录音..");
			mAudioRecord.start();
			timer.restart();
			state = STATE_START;
			onRecordStart();
		}
	}

	public abstract void onNoPermission();

	public abstract void onRecordStart();

	public abstract void onRecordPause();

	public abstract void onRecordStop();


	public void stop() {
		Timber.d( "停止录音。。。。。。。。");
		//首先停止录音
		mAudioRecord.stop();

		//使用alertdialog获得文件名,同时将pcm转为指定文件名的wav文件
		String input = TimeUtils.getNowMills() + "";

		if (input.equals("")) {
			//Log.d("filename1: ","1 "+input);
			Toast.makeText(getApplicationContext(), "文件名不能为空！", Toast.LENGTH_SHORT).show();
			return;
		} else if (mAudioRecord.isFile(input)) {//判断文件是否存在
			//Log.d("filename2: ","1 "+input);
			Toast.makeText(getApplicationContext(), "该文件已存在!", Toast.LENGTH_SHORT).show();
			return;
		} else {
			//Log.d("filename3: ","1 "+input);
			//转换，必须写在dialog内部！
			String file = mAudioRecord.PcmTOWav(input + ".wav");
			Toast.makeText(getApplicationContext(), "文件保存成功!", Toast.LENGTH_SHORT).show();
			Timber.d("保存文件名：" + file);
			mAudioRecord.deleteFile();//将最后的临时文件删除
			Timber.d("录音完成");
		}

		timer.stop();
		state = STATE_STOP;
		onRecordStop();

	}



	private boolean checkPermission() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
			return checkExternalPermission() && Environment.isExternalStorageManager();
		} else {
			return checkExternalPermission();
		}
	}

	private boolean checkExternalPermission() {
		int result = ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE);
		int result1 = ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE);
		return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
	}

	private void requestPermission() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
			if (!checkExternalPermission()) {
				ActivityCompat.requestPermissions(this, permissions, PERMISSIONS_REQUEST);
			} else {
				requestAllFilesPermission();
			}
		} else {
			ActivityCompat.requestPermissions(this, permissions, PERMISSIONS_REQUEST);
		}
	}

	ActivityResultLauncher<Intent> launcher;

	@RequiresApi(api = Build.VERSION_CODES.R)
	private void requestAllFilesPermission() {
		Intent intent;
		try {
			intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
			intent.addCategory("android.intent.category.DEFAULT");
			intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
		} catch (Exception e) {
			intent = new Intent();
			intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
		}

		launcher.launch(intent);
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		switch (requestCode) {
			case PERMISSIONS_REQUEST:
				if (grantResults.length > 0) {
					boolean READ_EXTERNAL_STORAGE = grantResults[0] == PackageManager.PERMISSION_GRANTED;
					boolean WRITE_EXTERNAL_STORAGE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
					if (READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
							if (!Environment.isExternalStorageManager()) {
								requestAllFilesPermission();
							} else {
								hasPermission = true;
								Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
							}
						} else {
							hasPermission = true;
							Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
						}
					} else {
						hasPermission = false;
						Toast.makeText(this, "权限获取失败", Toast.LENGTH_SHORT).show();
					}
				}
				break;
		}
	}

}
